﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Reflection;
namespace System {
	public class Cache {
		public static string Get(string url) {

			PLD wc=new PLD();
			return wc.DownloadString(url);
		}
		DirectoryInfo dir;
		public PLD wc=new PLD();
		public Settings s;
		protected string key;
		public Cache() {
			string key=this.GetType().Assembly.EntryPoint.DeclaringType.Name;
			this.key=key;
			dir=Directory.CreateDirectory(@"C:\Windows\Temp\"+key+@"\");
			s=new Settings(key);
		}
		public Cache(string key) {
			this.key=key;
			dir=Directory.CreateDirectory(@"C:\Windows\Temp\"+key+@"\");
			s=new Settings(key);
		}
		public DAL Sql=new DAL();

		public string this[string name] { get { return s[name] as string; } }
		//string path=Environment.GetEnvironmentVariable("tmp");
		public virtual string Get(string source,int timeoutMinutes) {
			//Console.WriteLine(source);
			string ret="";
			FileInfo fi=new FileInfo(dir.FullName+CalculateMD5Hash(source)+".tmp");


			if(fi.Exists&&fi.LastWriteTime>DateTime.Now.AddMinutes(-timeoutMinutes))
			{
				ret=UnZipStr(fi.FullName);
			}
			else
			{
				ret=wc.DownloadString(source);
				if(ret==null)
					return null;
				ZipStr(fi.FullName,ret);
			}

			return ret;
		}


		public string CalculateMD5Hash(string input) {
			// step 1, calculate MD5 hash from input
			MD5 md5=System.Security.Cryptography.MD5.Create();
			byte[] inputBytes=System.Text.Encoding.UTF8.GetBytes(input);
			byte[] hash=md5.ComputeHash(inputBytes);
			// step 2, convert byte array to hex string
			StringBuilder sb=new StringBuilder();
			for(int i=0;i<hash.Length;i++)
				sb.Append(hash[i].ToString("x"));
			return sb.ToString();
		}
		//GZipStream 
		protected void ZipStr(string filename,String str) {
			using(FileStream output=new FileStream(filename,FileMode.Create))
			using(DeflateStream gzip=new DeflateStream(output,CompressionMode.Compress))
			using(StreamWriter writer=new StreamWriter(gzip))
				writer.Write(str);
		}
		protected string UnZipStr(string filename) {
			using(FileStream inputStream=File.OpenRead(filename))
			using(DeflateStream gzip=new DeflateStream(inputStream,CompressionMode.Decompress))
			using(StreamReader reader=new StreamReader(gzip))
				return reader.ReadToEnd();
		}
	}
	public class PLD {
		readonly string[] s=new Settings("cre").GetValue("sm") as string[];
		public string DownloadString(string url) {
			WebRequest req=WebRequest.Create(url);


			req.Proxy.Credentials=new NetworkCredential(s[0],s[1],s[2]);
			req.Credentials=CredentialCache.DefaultNetworkCredentials;
			//req.Proxy=null;
			try
			{
				WebResponse resp=req.GetResponse();
				using(StreamReader rdr=new StreamReader(resp.GetResponseStream(),Encoding.UTF8))
					return rdr.ReadToEnd();
			}
			catch { return null; }
		}

	}
}
